package com.guojian.common.http;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.Header;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.nio.client.CloseableHttpAsyncClient;
import org.apache.http.impl.nio.client.HttpAsyncClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.lang.NonNull;
import org.springframework.util.Base64Utils;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSONObject;

import cn.hutool.core.util.StrUtil;

/**
 * @author guojian
 */
public class HttpUtils {

	private static CloseableHttpClient HTTPCLIENT = HttpClients.createSystem();

	/*private static CloseableHttpAsyncClient ASYNC_HTTPCLIENT = HttpAsyncClients.createDefault();
	
	static {
		ASYNC_HTTPCLIENT.start();
	}*/

	public static Response get(String url) {
		HttpUriRequest httpRequest = RequestBuilder.get().setUri(url).build();
		return doHttpProcess(httpRequest);
	}

	public static Response postJson(@NonNull String url, @NonNull String json) {
		HttpUriRequest httpRequest = RequestBuilder.post().setUri(url).setEntity(new StringEntity(json, ContentType.APPLICATION_JSON)).build();
		return doHttpProcess(httpRequest);
	}

	public static Response postXML(@NonNull String url, @NonNull String json) {
		HttpUriRequest httpRequest = RequestBuilder.post().setUri(url).setEntity(new StringEntity(json, ContentType.create("application/xml", Charset.forName("GBK")))).build();
		return doHttpProcess(httpRequest);
	}

	// List<NameValuePair> nameValuePairs = convertMapParamsToList(nameValues);
	public static Response post(String url, Map<String, String> params) {
		List<NameValuePair> nameValuePairs = convertMapParamsToList(params);
		HttpUriRequest httpRequest = RequestBuilder.post().setUri(url).addParameters(nameValuePairs.toArray(new NameValuePair[0])).build();
		return doHttpProcess(httpRequest);
	}

	public static Response doHttpProcess(HttpUriRequest httpRequest) {
		setDefaultHeader(httpRequest);
		try {
			return Response.create(executeHttp(httpRequest));
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	/*public static CloseableHttpResponse doHttpProcess(HttpRequest request, String url, HttpEntity entity) {
		HttpUriRequest httpUriRequest = RequestBuilder.create(request.getMethod()).setUri(url).setEntity(entity).build();
		setTargetHeader(request, httpUriRequest);
		try {
			return HTTPCLIENT.execute(httpUriRequest);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}*/

	/**
	 * @param httpRequest
	 * @return
	 */
	public static CloseableHttpResponse doHttpClientProcess(HttpUriRequest httpRequest) {
		try {
			return HTTPCLIENT.execute(httpRequest);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	/*public static Future<HttpResponse> doAsyncSmartHttpProcess(HttpUriRequest httpRequest) {
		return ASYNC_HTTPCLIENT.execute(httpRequest, null);
	}*/

	/**
	 * 参数类型转换
	 *
	 * @param nameValues
	 * @return
	 */
	public static List<NameValuePair> convertMapParamsToList(Map<String, String> nameValues) {
		List<NameValuePair> nvps = new ArrayList<NameValuePair>();
		if (nameValues != null) {
			for (String name : nameValues.keySet()) {
				nvps.add(new BasicNameValuePair(name, nameValues.get(name)));
			}
		}
		return nvps;
	}

	private static void setDefaultHeader(HttpUriRequest request) {
		List<Header> headers = new ArrayList<Header>();
		headers.add(new BasicHeader("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.79 Safari/537.36"));
		headers.add(new BasicHeader("Connection", "keep-alive"));
		headers.add(new BasicHeader("Cache-Control", "no-cache"));
		Header[] headersObject = new Header[headers.size()];
		request.setHeaders(headers.toArray(headersObject));
	}

	private static CloseableHttpResponse executeHttp(HttpUriRequest httpRequest) throws IOException, ClientProtocolException {
		return HTTPCLIENT.execute(httpRequest);
	}

	public static void main(String[] args) {
		//test11();
		//Response response = post("http://128.1.108.215:8079/config", null);
		//String bbb = response.toString();
		//System.out.println(bbb);

		//testSchool();

		testp8_tytx();

		//base64encode();

		//testp8_hustdz();

	}

	public static void testp8_tytx() {
		try {
			String xml = FileUtils.readFileToString(new File("E:/tytx/requestP8_001.xml"));
			System.out.println(xml);

			Map<String, String> parmas = new HashMap<>();
			parmas.put("body", xml);

			//Response response = HttpUtils.post("http://localhost:9091/ccb-server/hustDz/hust001", parmas);
			//Response response = HttpUtils.postJson("http://localhost:8080/qykh-server-1.0.0/hustDz/hust001", json);
			//Response response = HttpUtils.post("http://128.1.108.235:8101/hustdz-server-10281/hustDz/hust001", parmas);
			//Response response = HttpUtils.post("http://128.1.108.235:8101/hustdz-server-1025/http", parmas);
			//Response response = HttpUtils.postXML("http://128.1.108.235:8101/hbqykh-web/httpService", xml);//http://128.1.108.235:8101/hbqykh-web
			//Response response = HttpUtils.postXML("http://localhost:9092/tytx/http", xml);
			//	http://128.1.108.155:8101/tytx-web
			//Response response = HttpUtils.postXML("http://128.1.108.155:8101/tytx-web/httpService", xml);
			Response response = HttpUtils.postXML("http://128.1.108.235:8101/tytx-web/httpService", xml);
			System.out.println(response.toString());

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static void base64encode() {

		try {
			byte[] filebyte = FileUtils.readFileToByteArray(new File("D:/xmlwydz/request002.txt"));
			byte[] base64byte = Base64Utils.encode(filebyte);

			String xml = new String(base64byte, "GBK");

			System.out.println(xml);

			//Response response = HttpUtils.postXML("http://localhost:9091/ccb-server/httpService", );
			//System.out.println(response.toString());

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void testp8_hustdz() {
		try {
			String xml = FileUtils.readFileToString(new File("D:/xmlwydz/requestP8_002.xml"));
			System.out.println(xml);

			Map<String, String> parmas = new HashMap<>();
			parmas.put("body", xml);

			//Response response = HttpUtils.post("http://localhost:9091/ccb-server/hustDz/hust001", parmas);
			//Response response = HttpUtils.postJson("http://localhost:8080/qykh-server-1.0.0/hustDz/hust001", json);
			//Response response = HttpUtils.post("http://128.1.108.235:8101/hustdz-server-10281/hustDz/hust001", parmas);
			//Response response = HttpUtils.post("http://128.1.108.235:8101/hustdz-server-1025/http", parmas);
			//Response response = HttpUtils.postXML("http://128.1.108.235:8101/hbqykh-web/httpService", xml);//http://128.1.108.235:8101/hbqykh-web
			Response response = HttpUtils.postXML("http://128.5.108.239:9091/ccb-server/httpService", xml);
			System.out.println(response.toString());

		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void testSchool() {
		Map<String, String> abc = new HashMap<String, String>();
		abc.put("shId", "42000001");//42000001//420000008//42010001//420000002
		//abc.put("shId", "420000002");
		abc.put("stId", "3919773545");//3919773545
		abc.put("name", "张三");
		//abc.put("type", "notify");
		abc.put("type", "query");

		//Response response = post("http://128.1.108.215:8079/config", abc);

		Response response = post("http://localhost:8079/config", abc);
		System.out.println(response.toString());
	}

	public static void nioTest() {
		CloseableHttpAsyncClient client = HttpAsyncClients.createDefault();
		client.start();
		Future<HttpResponse> responseFuture = client.execute(RequestBuilder.get("http://www.baidu.com").build(), null);
		try {
			HttpResponse response = responseFuture.get();
			System.out.println(response.getStatusLine().getReasonPhrase());
			//System.out.println(EntityUtils.toString(response.getEntity()));
		} catch (ParseException | InterruptedException | ExecutionException e) {
			e.printStackTrace();
		} finally {
			try {
				client.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@SuppressWarnings("rawtypes")
	public static void test2() {
		//RestTemplateBuilder builder = new RestTemplateBuilder().requestFactory(HttpComponentsClientHttpRequestFactory.class);
		//builder.build();
		RestTemplate restTemplate = new RestTemplate(new HttpComponentsClientHttpRequestFactory());
		HttpHeaders httpHeader = new HttpHeaders();
		//httpHeader.add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_FORM_URLENCODED_VALUE);

		MultiValueMap<String, Object> params = new LinkedMultiValueMap<>();
		params.add("name", "guojian");
		params.add("age", 19);

		/*MultiValueMap params = new MultiValueMap();
		params.put("name", "guojian");
		params.put("age", 19);*/

		org.springframework.http.HttpEntity<MultiValueMap<String, Object>> httpEntity = new org.springframework.http.HttpEntity<MultiValueMap<String, Object>>(params, httpHeader);
		ResponseEntity<Map> response = restTemplate.postForEntity("http://localhost:8027/testPost", httpEntity, Map.class);

		System.out.println("===============" + response.getBody());
	}

	public static void test11() {
		JSONObject object = new JSONObject();
		object.put("name", "guojian");
		object.put("age", 12);

		/* http request params: name=[SIGNTYPE],value=[MD5]
		   http request params: name=[Cst_Nm],value=[张三]
		   http request params: name=[SIGN],value=[68edbb8360677db93a982d4aa2c4e5f6]
		http request params: name=[Shl_id],value=[42000001]
		http request params: name=[St_id],value=[202003704586]
		*/

		Map<String, String> abc = new HashMap<String, String>();
		abc.put("SIGNTYPE", "MD5");
		abc.put("SIGN", "d4b068296d9c1fd7cb239bb7b9de07cf");
		//abc.put("SIGN", "d4b068296d9c1fd7cb239bb7b9de07cf");
		abc.put("Shl_id", "42000001");
		abc.put("St_id", "3919773545");//3919773545
		//abc.put("St_id", "3919773545");//
		abc.put("Cst_Nm", "张三");

		/*abc.put("SIGNTYPE", "MD5");
		abc.put("SIGN", "41be612ef86b06bbaebffd255f2c0632");
		abc.put("Shl_id", "42000001");
		abc.put("St_id", "9876543210");*/

		/*name=[SIGNTYPE],value=[MD5]
		name=[SIGN],value=[41be612ef86b06bbaebffd255f2c0632]
		name=[Shl_id],value=[42000001]
		name=[St_id],value=[9876543210]*/

		Response response = post("http://localhost:8079/transfQuery", abc);//128.1.108.215:8079

		//Response response = post("http://localhost:8079/transfNotify", abc);//128.1.108.215:8079

		//Response response = post("http://128.1.108.215:8079/transfNotify", abc);
		String bbb = response.toString();
		System.out.println(bbb);

	}

}
